﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO.Compression;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.IO;

namespace chatblog
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {
            // 在新会话启动时运行的代码
            Session.Timeout = 10; //设置Session的有效时间，可根据需要修改
            Application.Lock();
            Application["zzzonline"] = Convert.ToInt32(Application["zzzonline"]) + 1;
            Application.UnLock();
        }

        #region SQL注入式攻击代码分析
        /// <summary> 
        /// 处理用户提交的请求 
        /// </summary> 
        private void StartProcessRequest()
        {
            try
            {
                string getkeys = "";
                System.Web.UI.Control c = new System.Web.UI.Control();
                string sqlErrorPage = c.ResolveUrl("~/ErrorLog/Log.aspx");
                if (System.Web.HttpContext.Current.Request.QueryString != null)
                {

                    //具有针对性的注入： 
                    string url = System.Web.HttpContext.Current.Request.Url.ToString();
                    string sInject = ".jsssss";
                    string s2 = "fuckuu.us";
                    if (url.IndexOf(sInject) >= 0 || url.IndexOf(s2) >= 0)
                    {
                        System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);
                        System.Web.HttpContext.Current.Response.End();
                    }

                    for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++)
                    {
                        getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];
                        if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys]))
                        {
                            sqlErrorPage += "?preUrl=" + HttpUtility.UrlEncode(Request.Url.ToString());//转向的错误提示页面 


                            DateTime dt = DateTime.Now;
                            string fileName = Server.MapPath("/ErrorLog") + "\\Log" + dt.ToString("yyyy_MM_dd") + ".log";
                            string content = dt.ToString() + "," + Request.UserHostAddress + "," + Request.Url.ToString() + "\r\n";
                            File.AppendAllText(fileName, content);
                            



                            //System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);
                            System.Web.HttpContext.Current.Response.End();
                        }
                    }


                }
                if (System.Web.HttpContext.Current.Request.Form != null)
                {
                    for (int i = 0; i < System.Web.HttpContext.Current.Request.Form.Count; i++)
                    {
                        getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i];
                        if (getkeys == "__VIEWSTATE") continue;
                        if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys]))
                        {
                            sqlErrorPage += "?preUrl=" + HttpUtility.UrlEncode(System.Web.HttpContext.Current.Request.Form[getkeys]);


                            DateTime dt = DateTime.Now;
                            string fileName = Server.MapPath("/ErrorLog") + "\\Log" + dt.ToString("yyyy_MM_dd") + ".log";
                            string content = dt.ToString() + "," + Request.UserHostAddress + "," + System.Web.HttpContext.Current.Request.Form[getkeys] + "\r\n";
                            File.AppendAllText(fileName, content);



                            //System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);
                            System.Web.HttpContext.Current.Response.End();
                        }
                    }
                }



            }
            catch(Exception ex)
            {
                // 错误处理: 处理用户提交信息! 
            }
        }
        /// <summary> 
        /// 分析用户请求是否正常 
        /// </summary> 
        /// <param name="Str">传入用户提交数据 </param> 
        /// <returns>返回是否含有SQL注入式攻击代码 </returns> 
        private bool ProcessSqlStr(string Str)
        {
            bool ReturnValue = true;
            try
            {
                if (Str.Trim() != "")
                {
                    string SqlStr = "exec|chr |mid |master |truncate |char |declare ";

                    string[] anySqlStr = SqlStr.Split('|');
                    foreach (string ss in anySqlStr)
                    {
                        if (Str.ToLower().IndexOf(ss.Trim()) >= 0)
                        {
                            ReturnValue = false;
                            break;
                        }
                    }
                }
            }
            catch
            {
                ReturnValue = false;
            }
            return ReturnValue;
        }

        #endregion
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            StartProcessRequest();
           // GZipCompresser(sender);
                                   
            //swfupload上传相关
            dealSwfuploadSession();
        }
        private void GZipCompresser(object sender)
        {
            HttpApplication app = (HttpApplication)sender;
            string acceptEncoding = app.Request.Headers["Accept-Encoding"];
            Stream prevUncompressedStream = app.Response.Filter;

            if (acceptEncoding == null || acceptEncoding.Length == 0)
                return;

            acceptEncoding = acceptEncoding.ToLower();

            if (acceptEncoding.Contains("gzip"))
            {
                // gzip
                app.Response.Filter = new GZipStream(prevUncompressedStream,
                    CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding",
                    "gzip");
            }
            else if (acceptEncoding.Contains("deflate"))
            {
                // defalte
                app.Response.Filter = new DeflateStream(prevUncompressedStream,
                    CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding",
                    "deflate");
            }

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {
            // 在会话结束时运行的代码。
            // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
            // InProc 时，才会引发 Session_End 事件。如果会话模式设置为 StateServer
            // 或 SQLServer，则不会引发该事件。
            Application.Lock();
            Application["zzzonline"] = Convert.ToInt32(Application["zzzonline"]) - 1;
            Application.UnLock();
        }

        protected void Application_End(object sender, EventArgs e)
        {

        }


        #region swfupload
        void UpdateCookie(string cookie_name, string cookie_value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
            if (cookie == null)
            {
                cookie = new HttpCookie(cookie_name);
                HttpContext.Current.Request.Cookies.Add(cookie);
            }
            cookie.Value = cookie_value;
            HttpContext.Current.Request.Cookies.Set(cookie);
        }

        void dealSwfuploadSession()
        {
            /* Fix for the Flash Player Cookie bug in Non-IE browsers.
         * Since Flash Player always sends the IE cookies even in FireFox
         * we have to bypass the cookies by sending the values as part of the POST or GET
         * and overwrite the cookies with the passed in values.
         * 
         * The theory is that at this point (BeginRequest) the cookies have not been read by
         * the Session and Authentication logic and if we update the cookies here we'll get our
         * Session and Authentication restored correctly
         */

            try
            {
                string session_param_name = "ASPSESSID";
                string session_cookie_name = "ASP.NET_SESSIONID";

                if (HttpContext.Current.Request.Form[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 500;
                Response.Write("Error Initializing Session");
            }

            try
            {
                string auth_param_name = "AUTHID";
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request.Form[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
                }

            }
            catch (Exception)
            {
                Response.StatusCode = 500;
                Response.Write("Error Initializing Forms Authentication");
            }
        }
        #endregion
    }
}
